package com.bidv.wcm;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;

import com.ibm.workplace.wcm.api.Content;
import com.ibm.workplace.wcm.api.Document;
import com.ibm.workplace.wcm.api.DocumentId;
import com.ibm.workplace.wcm.api.Identity;
import com.ibm.workplace.wcm.api.Repository;
import com.ibm.workplace.wcm.api.RichTextComponent;
import com.ibm.workplace.wcm.api.VirtualPortalContext;
import com.ibm.workplace.wcm.api.WCM_API;
import com.ibm.workplace.wcm.api.Workspace;
import com.ibm.workplace.wcm.api.query.Query;
import com.ibm.workplace.wcm.api.query.ResultIterator;
import com.ibm.workplace.wcm.api.query.Selectors;

/**
 * Servlet implementation class GetContent
 */
@WebServlet("/GetContentVideo")
public class GetContentVideo extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GetContentVideo() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		byte[] data = null;
		InputStream is = null;
	    String range = request.getHeader("range");
        String browser = request.getHeader("User-Agent");
		try {
			Repository repo = WCM_API.getRepository();
			VirtualPortalContext vctx = repo.generateVPContextFromContextPath(request.getParameter("Context"));
			VPContentVideo vpA = new VPContentVideo();
			vpA.requestID = request.getParameter("ID");
			vpA.doclib = request.getParameter("DocLib");
			WCM_API.getRepository().executeInVP(vctx, vpA);
			is = vpA.is;
			
		} catch (Exception Ex){
			
		}
		String diskfilename = "final.mp4";
        response.setContentType("video/mp4");
        //response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + diskfilename + "\"" );
        System.out.println("data.length " + data.length);
        response.setContentLength(data.length);
        response.setHeader("Content-Range", range + Integer.valueOf(data.length-1));
        response.setHeader("Accept-Ranges", "bytes");
        response.setHeader("Etag", "W/\"9767057-1323779115364\"");
        byte[] content = new byte[1024];
        while (is.read(content) != -1) {
            //System.out.println("... write bytes");
        	response.getOutputStream().write(content);
        }
		is.close();
		response.getOutputStream().close();
	}

}
